<?php

namespace IDock\Common\Encrypt;

/***
 * RSA 签名
 */
class RSAEncrypt
{

    /**
     * 私钥
     * @var string $privateKey
     */
    public $privateKey = '';

    /**
     * 公钥
     * @var string $publicKey
     */
    public $publicKey = '';

    /**
     * 待加密字符串
     * @var string $toSignString
     */
    public $toSignString = '';

    /**
     * 加密类型 RSA or RSA2
     * @var string $signType
     */
    protected $signType = 'RSA2';

    public function SignTypeRSA()
    {
        $this->signType = 'RSA';
    }

    public function signTypeRSA2()
    {
        $this->signType = 'RSA2';
    }

    public function setPublicKey(string $publicKey)
    {
        if (preg_match('/PUBLIC/', $publicKey)) {
            $this->publicKey = $publicKey;
        } else {
            $this->publicKey = "-----BEGIN PUBLIC KEY-----\n" .
                wordwrap($publicKey, 64, "\n", true) .
                "\n-----END PUBLIC KEY-----";
        }
    }


    /**
     * 公钥加密
     * @param string $toEnString
     * @return string
     * @version 4.0
     */
    public function publicEncrypt(string $toEnString): string
    {
        $publicKey = $this->publicKey;

        openssl_public_encrypt($toEnString, $encrypted, $publicKey);
        $encrypted = base64_encode($encrypted);

        return $encrypted;

    }
}
